package com.jt.blog.exception;

import com.google.common.base.Throwables;
import com.jt.blog.common.exception.JsonResponseException;
import com.jt.blog.common.model.ExceptionDto;
import com.jt.blog.common.util.DateKit;
import com.jt.blog.common.util.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

/**
 * @author : 戴瑞
 * @Description :
 * @create : 2018-03-25 16:29
 **/


@ControllerAdvice
public class GlobalException {



    @ExceptionHandler
    public Object handlerAllException(Exception e, HttpServletRequest request, HttpServletResponse response){
        ExceptionDto dto;
        String dateFormat = DateKit.dateFormat(new Date(), "yyyy-MM-dd HH:mm:ss");
        String path= request.getRequestURI();
        if (isAjax(request))
        {
            // 判断是否是rest风格或者ajax的请求出错
            if (e instanceof JsonResponseException){
                JsonResponseException exception =(JsonResponseException)e;
                dto=new ExceptionDto( exception.getStatus(),exception.getMessage(),
                        path,dateFormat);
            }else {
                dto=new ExceptionDto(HttpStatus.INTERNAL_SERVER_ERROR.value(),"Internal Error",path,dateFormat);
            }

            String json = JsonUtils.objectToJson(dto);
            try {
                response.setHeader("Content-Type","application/json");
                response.getWriter().print(json);

            } catch (IOException e1) {
                dto=new ExceptionDto(HttpStatus.INTERNAL_SERVER_ERROR.value(),"IOException",path,dateFormat);
                String jsonIO = JsonUtils.objectToJson(dto);
                try {
                    response.getWriter().print(jsonIO);
                } catch (IOException e2) {
                    e2.printStackTrace();
                }
            }
        }else {
            // 普通的页面请求出错
            ModelAndView modelAndView=new ModelAndView();
            modelAndView.setStatus(HttpStatus.INTERNAL_SERVER_ERROR);
            modelAndView.addObject("error", "500!  Internal Error: "+e.getMessage());
            modelAndView.setViewName("front/error");
            return modelAndView;
        }
        return null;

    }

    private boolean isAjax(HttpServletRequest request) {
        return (request.getHeader("X-Requested-With") != null && "XMLHttpRequest".equals(request.getHeader("X-Requested-With")));
    }
}
